package com.example.auth.config.exception;

import com.alibaba.fastjson.JSONObject;
import com.example.auth.config.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@Slf4j
public class ExcetionConfig {

    /**
     * 校验组件使用
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public JSONObject serviceHandle(MethodArgumentNotValidException e) {
        log.info("有异常");
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(allErrors.get(0).getDefaultMessage());
        log.info(stringBuilder.toString());
        return ResultUtil.errorInfo(stringBuilder.toString());
    }


    @ExceptionHandler(value = GlobalExcetion.class)
    @ResponseBody
    public JSONObject serviceHandle(GlobalExcetion e) {
        log.info("异常信息异常码: {} 自定义异常信息:{} 系统异常信息:{}",e.getCode(),e.getMsg(),e.getMessage());
        return ResultUtil.msg(e.getCode(),e.getMsg());
    }


    @ExceptionHandler(value = SecurityException.class)
    @ResponseBody
    public JSONObject serviceHandle(SecurityException e) {
        log.info(" 系统异常信息:{}",e.getMessage());
        return ResultUtil.msg(1,e.getMessage());
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public JSONObject serviceHandle(BindException e) {
        e.printStackTrace();
        BindingResult result=e.getBindingResult();
        List<ObjectError> allErrors= e.getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for(ObjectError objectError:allErrors){
            stringBuilder.append(objectError.getDefaultMessage());
        }
      //  System.out.println(JSONObject.toJSONString(result));
        return ResultUtil.msg(1,stringBuilder.toString());
    }
}
